// 根据所需类型进行转码并返回下载地址
export function setEncoded(type: string, filename: string, data: string) {
  const encodedData: string = encodeURIComponent(data)
  let mimeType: string;

  switch (type.toLowerCase()) {
    case 'svg':
      mimeType = 'text/xml';
      break;
    case 'json':
      mimeType = 'application/json';
      break;
    default:
      mimeType = 'application/bpmn20-xml';
  }

  return {
    filename: `${filename}.${type.toLowerCase()}`,
    href: `data:${mimeType};charset=UTF-8,${encodedData}`,
    data: data
  };
}

// 文件下载方法
export function downloadFile(href: string, filename: string) {
  if (href && filename) {
    const a: HTMLAnchorElement = document.createElement('a')
    a.download = filename //指定下载的文件名
    a.href = href //  URL对象
    document.body.appendChild(a);
    a.click() // 模拟点击
    document.body.removeChild(a)
    URL.revokeObjectURL(a.href) // 释放URL 对象
  }
}
// JSON 下载方法
export function downloadJSON(data: object | string, filename: string = 'data') {
  const jsonString = typeof data === 'string' 
    ? data 
    : JSON.stringify(data, null, 2);
  const { href, filename: fullName } = setEncoded('json', filename, jsonString);
  downloadFile(href, fullName);
}
